<?php
namespace YzPay\Controller\Home;
//use Think\Controller;
class UserController extends CommonController {
	public function _initialize() {
		parent::_initialize();

	}

	//操作当为空的时候
	public function _empty($name) {
		ob_start();
		$GLOBALS['GETCONTENT'] = 1;
		A("BoxSns/Home/User")->$name();
		$this->user_page_content = ob_get_contents();
		ob_end_clean();
		C('DEFAULT_MODULE', "YzPay");
		$this->page_content = $this->fetch("User/home");
		$templateFile = $this->getTemplateFile("Index/home");
		parent::display($templateFile);
	}
	function test() {

		// $appId = "1441071499740581";
		// $md5Key = "DK96gnOB7EmVDDaHgLTLEZqVgP0H0nML";
		// $des3Key = "Z5CbXbEaJA6CYRSDS5Ddsab6";
		// $url = "http://posp.ipaynow.cn:20320";
		$req = array();
		//验证银行卡信息
		$config = array(
			'app_id' => '1441071499740581',
			'md5_key' => 'DK96gnOB7EmVDDaHgLTLEZqVgP0H0nML',
			'des_key' => 'Z5CbXbEaJA6CYRSDS5Ddsab6',
			'trans_url' => 'http://posp.ipaynow.cn:20320',
			'query_url' => 'http://www.codecamp.com/',
			'check_funcode' => 'ID02',
		);
		$req["bankCardNum"] = "6225882141094356"; //银行账户
		$req["certiType"] = "01"; //证件类型
		$req["funcode"] = "ID02";
		$req["idCard"] = "4414241989081765784"; //身份证号
		$req["idCardName"] = "温作权"; //姓名
		$req["mhtOrderNo"] = date("YmdHis");
		$req["mobile"] = "18513916473"; //手机号
		$Services = new \Common\Org\AgentPay\Services($config);
		$req_content = $Services->buildAndSendCheckReq($req);
		dump($req_content);
		parse_str($req_content, $parr);
		dump($parr);

		//代发业务
		$config = array(
			'app_id' => '1459846530407363',
			'md5_key' => 'oAKsBv38CcLdnIn5N733oiY81erfotAC',
			'des_key' => 'e2KSP6awXjkbfm8eR3iE2BmW',
			'trans_url' => 'https://dby.ipaynow.cn/agentpay/agentPay',
			'query_url' => 'http://yzpay.boxphp.me//',
			'check_funcode' => 'AP04',
		);
		$req = array();
		$req["agentPayMemo"] = "test";
		$req["funcode"] = "AP04";
		$req["mhtOrderNo"] = date("YmdHis");
		$req["mhtReqTime"] = date("YmdHis");
		$req["payeeAccType"] = "02";
		$req["payeeName"] = "中国";
		$req["payeeCardNo"] = "38511234864324000";
		$req["mhtOrderAmt"] = "301";
		$Services = new \Common\Org\AgentPay\AgentPayServices($config);
		$req_content = $Services->buildAndSendCheckReq($req);
		dump($req_content);
		parse_str($req_content, $parr);
		dump($parr);
		//Log::outLog("验证信息接口应答:", $req_content);

	}
	/******我的****/
	public function index() {
		$this->show_user();
	}

	//扫一扫支付
	public function pay() {
		$data = $this->user_info;
		if (!$data['store_name'] || !$data['phone']) {
			$this->redirect(U('edit'));
			exit();
		}

		$row = array('user_id' => $data['user_id'], 'name' => $data['name'], 'openid' => $data['openid'], 'store_name' => $data['store_name']);
		ksort($row);
		$sign = thinkEncrypt($row);
		$type = I('type', "Alipay");
		$configData = BoxModel("yz_payset")->where(array('name' => $type))->find();
		$config = json_decode($configData['paySet'], true);
		//生成支付二维码
		$params = array(
			'notify_url' => yzpayUrl . "/CallBack/paySuccess/type/" . $type, //回调地址
			'order_sn' => createOrderNo(),
			'total_amount' => '99', //金额
			'title' => $data['store_name'], //
			'extend_params' => array('sign' => $sign),
		);
		$payClass = new \Common\Org\YzPay\YzPay($type, $config);
		$req = $payClass->QRCode($params);
		$this->payUrl = $req['qr_code'];
		$this->show_user();
	}

	//完个人信息
	public function edit() {
		if (!$this->user_info['user_id']) {
			$this->jump("请先登录");
		}
		$this->data = $this->user_info;
		if (IS_POST) {
			//exit("1");
			$name = trim(I('name'));
			$store_name = trim(I('store_name'));
			if ($name == "" || $store_name == "") {
				$this->jump("姓名和商户名称不能为空");
			}
			$row = array(
				'user_id' => $this->user_info['user_id'],
				'name' => $name,
				'type' => 'YzPay',
			);
			BoxModel("system_member")->create_member($row);
			$row = array(
				'store_name' => $store_name,
				'user_id' => $this->user_info['user_id'],
			);
			if ($this->data) {
				$r = BoxModel("yz_member")->save($row);
			} else {
				$row['add_time'] = time();
				$r = BoxModel("yz_member")->add($row);
			}
			if ($r !== false) {
				exit(json_encode(array('error' => 0, 'msg' => '信息保存成功')));
				//$this->jump("信息保存成功");
			} else {
				exit(json_encode(array('error' => 1, 'msg' => '信息保存失败')));
				//$this->jump("信息保存失败");
			}

		}
		$this->show_user();
	}
//订单列表
	public function order() {
		$pay = I('pay', "itntval", 2);
		$where = "type = 'avail_money'";
		$user_id = $this->user_info['user_id'];
		if ($pay == 2) {
			$where .= " and pay_user_id='$user_id'";
		} else {
			$where .= " and user_id='$user_id'";
		}
		//dump($this->user_info);
		//Logic("YzPay", "User")->inc_money("GA232442871902d");
		//dump($where);
		$data = BoxModel("system_log")->get($where, "10");
		$model = BoxModel("system_money_withdraw");
		$status_array = array(
			'1' => '提现中',
			'2' => '成功',
			'3' => '失败',
		);
		foreach ($data['list'] as $k => $one) {
			if ($one['event'] == '00024') {
				$logs = $model->where(array('logId' => $one['id']))->find();
				$data['list'][$k]['status_text'] = $status_array[$logs['status']];
			}
		}
		//dump();
		$this->data = $data['list'];
		$this->show_page($data['pager']);
		//dump($this->data);
		$this->show_user();
	}
	//提现
	function withdraw() {
		$data = BoxModel("system_withdraw_setting")->where(array('user_id' => $this->user_info['user_id']))->find();
		$setting = (array) json_decode($data['setting'], true);
		if (!$setting['account']) {
			$this->redirect(U('withdraw_set'));
			exit();
		}
		$this->free_withdraw_count = 1;
		$setting['show_account'] = substr_replace($setting['account'], '', '0', strlen($setting['account']) - 4);
		$this->account = $setting;
		$this->display();
	}
//提现申请
	function doWithdraw() {
		$money = $this->user_info['avail_money'];
		$withdraw_count = $this->user_info['withdraw_count'];
		$this->free_withdraw_count = 1; //1000以内有1次免费体验机会
		if ($money < 1000 && $withdraw_count > $this->free_withdraw_count) {
			$money = $money - 1;
			$this->setDecMoney = 1;
		}
		if (!($money > 0)) {
			exit(json_encode(array('error' => 1, 'msg' => '提现金额不能小于0')));
		}
		$model = BoxModel("yz_member");
		$model->startTrans(); //提现开事务
		BoxModel("system_log")->startTrans();
		//写到日志并资金减少
		$model->where(array('user_id' => $this->user_info['user_id']))->setInc('withdraw_count');
		$data = array(
			'user_id' => $this->user_info['user_id'],
			'num' => -$money,
			'event' => '00024',
		);
		$logReturn = Logic("BoxSns", "Log")->add($data); //日志
		//写到提现表
		if ($logReturn['update'] && $logReturn['logId']) {
			$withdrawSettingData = BoxModel("system_withdraw_setting")->where(array('user_id' => $this->user_info['user_id']))->find();
			$withdrawSetting = json_encode($withdrawSettingData['setting'], true);
			$row = array(
				'user_id' => $this->user_info['user_id'],
				'money' => $money,
				'addtime' => date("Y-m-d H:i:s"),
				'phone' => $this->user_info['phone'],
				'status' => 1,
				'logId' => $logReturn['logId'],
				'account' => $withdrawSettingData['setting'],
				'fee_withdraw' => $this->setDecMoney,
			);
			$withdrawId = BoxModel("system_money_withdraw")->add($row); //提现记录
		}

		//扣一元手续费
		$bool2 = true;
		if ($withdrawId && $this->setDecMoney) {
			$bool2 = BoxModel("system_member")->where(array('user_id' => $this->user_info['user_id']))->setDec("avail_money");
		}
		//数据写入成功
		if ($logReturn['update'] !== false && $logReturn['logId'] && $withdrawId && $bool2) {

			BoxModel("system_log")->commit();
			//代付
			$payClass = new \Common\Org\YzPay\YzPay();
			$param = array(
				'agentPayMemo' => "在柚子支付提现", //备注
				'money' => $money,
				'payeeCardNo' => $setting['account'],
				'payeeName' => $setting['name'],
			);
			$check = $payClass->angentPay($param);
			if ($check['responseCode'] == "A001") {
				$model->commit();
			} else {
				exit(json_encode(array('error' => 1, 'msg' => '提现失败,可联系管理员。系统错误:' . $check['responseMsg'])));
			}
			exit(json_encode(array('error' => 0, 'msg' => '提现已提交！')));
		} else {
			$model->rollback();
			BoxModel("system_log")->rollback();
			exit(json_encode(array('error' => 8, 'msg' => '数据处理失败，请重试')));
		}
	}

	function agent() {
		// BoxModel("system_member")->where(array('user_id' => '100349'))->delete();
		// BoxModel("system_sync_login")->where(array('uid' => '100349'))->delete();
		// BoxModel("yz_member")->where(array('user_id' => '100349'))->delete();
		//BoxModel("edu_students")->where(array('user_id' => '100349'))->delete();
		$param = BoxModel("addon_wx_config")->where(array('store_id' => $this->store_id))->find();
		$wechatObj = new \Common\Org\weiXin($param);
		//dump($this->user_id);
		$this->qrcodeUrl = $wechatObj->qrcode($this->user_id);
		$this->show_user();
	}

}